import {defineStore} from "pinia";
import { ref, computed } from 'vue'
import {useUserStore} from "@/stores/userStore.js";
import {delCartAPI, findNewCartListAPI, insertCartAPI,updateCartItem} from "@/api/cart.js";
export const useCartStore = defineStore(
    'cart',
    ()=>{
        const cartList = ref([]);
        const userStore =  useUserStore()
        const islogin = computed(()=>userStore.userInfo.token)
        //通过token值判断是否登录， 如果登录过就有token值
        //获取登录后的罪行购物车列表action
        const updateLoginCartList = async ()=>{
            const res = await findNewCartListAPI()
            cartList.value = res.result
            //获得最新的数据
        }
        const addCart = async (goods) => {
            if(islogin.value){
                await insertCartAPI(goods);
                await updateLoginCartList();


            }else {
                //判断商品是否在购物车
                const findItem = cartList.value.find(item => goods.skuId === item.skuId);
                if (findItem) {
                    findItem.count += goods.count;
                } else {
                    cartList.value.push(goods)
                }
            }
        }
        const delCart = async (skuId)=>{
            if(islogin.value){
                await delCartAPI([skuId]);
                await updateLoginCartList();
                //获取的最新的数据


            }
            const index = cartList.value.findIndex(item=>skuId === item.skuId)
            cartList.value.splice(index,1)
        }
        //全选功能
        const checkAll = (selected) =>{
            cartList.value.forEach(item => item.selected = selected)
        }
        //清除购物车
        const clearCart = ()=> {
            cartList.value = []

        }
        //修改购物项

        const updateCart = async (goods) => {
            const {skuId,count,selected} = goods
            if (islogin.value) {
                await updateCartItem(skuId,{count,selected})
            }

        }
        //是否全选的计算属性
        const isAll = computed(()=> cartList.value.every((item=>item.selected)))
        // 1. 总的数量 所有项的count之和
        const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
        // 2. 总价 所有项的count*price之和
        const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

        //已选择的数量
        const selectedCount = computed(()=>cartList.value.filter(item=>item.selected)
            .reduce((a,c) => a+c.count,0))

        //已选择的商品价钱合计
        const selectedPrice = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=> a + c.count * c.price,0))
        return{
            cartList,
            allPrice,
            allCount,
            addCart,
            delCart,
            checkAll,
            isAll,
            selectedCount,
            selectedPrice,
            updateLoginCartList,
            clearCart,
            updateCart

        }


    },
    {
        persist:true
    }
)